package com.chengjue.transaction.learn.nio.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

/**
 * 描述:
 *
 * @author Kipeng Huang
 * @create 2018-03-04 下午6:44
 */
public class Client {
	public static void main(String[] args) throws IOException {
		SocketChannel socketChannel = SocketChannel.open();
		socketChannel.configureBlocking(false);
		Selector selector = Selector.open();
		socketChannel.register(selector, SelectionKey.OP_CONNECT);
		socketChannel.connect(new InetSocketAddress("127.0.0.1", 8000));
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		while (true) {
			if (selector.select() > 0) {
				Set<SelectionKey> selectionKeys = selector.selectedKeys();
				Iterator<SelectionKey> iterator = selectionKeys.iterator();
				while (iterator.hasNext()) {
					SelectionKey key = iterator.next();
					if (key.isConnectable()) {
						SocketChannel client = (SocketChannel) key.channel();
						if (client.isConnectionPending()) {
							client.finishConnect();
							buffer.clear();
							// 向缓冲区中设置内容
							buffer.put(("isConnect,当前的时间为：" + new Date()).getBytes());
							buffer.flip();
							// 输出内容
							client.write(buffer);
						}
						client.register(selector, SelectionKey.OP_READ);
					} else if (key.isReadable() && key.isValid()) {
						SocketChannel client = (SocketChannel) key.channel();
						buffer.clear();
						// 读取内容到缓冲区中
						int readSize = client.read(buffer);
						if (readSize > 0) {
							System.out.println("客户端接受服务器端数据:" + new String(buffer.array(), 0, readSize));
							client.register(selector, SelectionKey.OP_WRITE);
						}
					} else if (key.isWritable() && key.isValid()) {
						SocketChannel client = (SocketChannel) key.channel();
						buffer.clear();
						// 向缓冲区中设置内容
						buffer.put(("nio文章学习很多！").getBytes());
						buffer.flip();
						// 输出内容
						client.write(buffer);
						client.register(selector, SelectionKey.OP_READ);
					}

				}
				selectionKeys.clear();

			}
		}
	}
}
